
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../pojo/ImPojo.dart';
import '../../socket/dto/business/WebRtcData.dart';
import '../../util/UiUtil.dart';
import '../bloc/WebRtcCubit.dart';
import 'WebRtcFloatingView.dart';
import 'component/LButton.dart';
import 'component/UiUtil.dart';
import 'component/UserIconView.dart';

/// invitationReq 为null时，表示用户主动发起视频聊天
/// invitationReq 不为null时， 表示用户被邀请视频聊天
class WebRtcAudioView extends StatelessWidget {

  OverlayEntry? overlayEntry = null;
  final WebRtcInvitationReq? invitationReq;

  WebRtcAudioView({ this.invitationReq, super.key});
  @override
  Widget build(BuildContext context) {
    var webRtcCubit = context.watch<WebRtcCubit>();
    return PopScope(onPopInvokedWithResult: (bool didPop, dynamic result){
      webRtcCubit.add(WebRtcSwitchScreenSmallEvent());
    }, child: _buildBody(context, webRtcCubit),);
  }

  Widget _buildBody(BuildContext context, WebRtcCubit webRtcCubit) {
    if (webRtcCubit.state.isScreenSmall) {
      return Stack(
        children: [
          _buildMainView(context, webRtcCubit),
        ],
      );
    } else {
      return Container(
        color: Colors.black,
        child: Stack(
          children: [
            _buildTitlePane(context, webRtcCubit),
            _buildMainView(context, webRtcCubit),
            if (webRtcCubit.state.isAccept && !webRtcCubit.state.isAccepted)
              _buildAcceptPane(context, webRtcCubit),

            if (!webRtcCubit.state.isAccept || webRtcCubit.state.isAccepted)
              _buildControlPane(context, webRtcCubit),
          ],
        ),
      );
    }
  }

  Widget _buildMainView(BuildContext context, WebRtcCubit webRtcCubit) {
    var state = webRtcCubit.state;
    var mediaList = state.mediaList;
    if (state.isScreenSmall) {
      if(mediaList.isNotEmpty) {
        var user = state.mediaList[0].user;
        return WebRtcFloatingView(child: _buildScreenSmallView(context, webRtcCubit, user), onTapFunction: () {
          webRtcCubit.add(WebRtcSwitchScreenSmallEvent());
        });
      } else {
        return const Text('');
      }
    }
    if (mediaList.isNotEmpty) {
      return _buildUsersPane(context, webRtcCubit);
    } else {
      return const Text('');
    }
  }

  Widget _buildTitlePane(BuildContext context, WebRtcCubit webRtcCubit) {
    String timeFormat = webRtcCubit.state.timeFormat;
    return Positioned(
        top: 100,
        left: 80,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            GestureDetector(
              onTap: (){
                if (webRtcCubit.state.mediaList.where((media)=>media.status == WebRtcUserDataStatus.connected).isNotEmpty) {
                  webRtcCubit.add(WebRtcSwitchScreenSmallEvent());
                }
              },
              child: buildSvgView('assets/webrtc-img/screen_small.svg', 30, 30, Colors.white),
            ),
            const SizedBox(width: 50,),
            Center(child: Text(timeFormat, style: const TextStyle(color: Colors.white, fontSize: 18,
                decoration: TextDecoration.none),),),
          ],
        ));
  }

  // 构建接受面板
  Widget _buildAcceptPane(BuildContext context, WebRtcCubit webRtcCubit) {
    return Positioned(
        top: 150,
        left: 10,
        right: 10,
        bottom: 60,
        child: Column(
          children: [
            _buildTipPane(context, webRtcCubit),                             // 连接提示信息栏
            const SizedBox(height: 80,),
            _buildAcceptOrRejectPane(context, webRtcCubit),                                      // 设置栏： 麦克风，扬声器， 摄像头
          ],
        ));
  }

  Widget _buildControlPane(BuildContext context, WebRtcCubit webRtcCubit) {
    return Positioned(
        top: 100,
        left: 10,
        right: 10,
        bottom: 60,
        child: Column(
          children: [
            _buildTipPane(context, webRtcCubit),                              // 连接提示信息栏
            const SizedBox(height: 80,),
            _buildSettingPane(context, webRtcCubit),                                      // 设置栏： 麦克风，扬声器， 摄像头
            const SizedBox(height: 30,),
          ],
        ));
  }

  Widget _buildUsersPane(BuildContext context, WebRtcCubit webRtcCubit) {
    var state = webRtcCubit.state;
    var loginUserId = UiUtil.getLoginUser().userId;
    var mediaList = state.mediaList.where((media)=>media.status != WebRtcUserDataStatus.offline
        && media.user.userId != loginUserId).toList();

    if (mediaList.length == 1) {
      var user = mediaList[0].user;
      return Center(child: SizedBox(width: 100, height: 100, child: _buildUserIcon(context, user),),);
    }

    var column = calcMediaColumn(mediaList);

    return Center(child: GridView.builder(
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: column, childAspectRatio: 1, crossAxisSpacing: 0.0, mainAxisSpacing: 0.0),
      shrinkWrap: true,
      itemCount: state.mediaList.length,
      itemBuilder: (BuildContext context, int index) {
        var user = state.mediaList[index].user;
        return _buildUserIcon(context, user);
      },
    ),);
  }

  Widget _buildSettingPane(BuildContext context, WebRtcCubit webRtcCubit) {
    var state = webRtcCubit.state;
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: [
        LButton(
          name: state.isCloseAudio ? '麦克风已关' : '麦克风已开',
          assetImage: state.isCloseAudio ? 'assets/webrtc-img/audio_close.svg' : 'assets/webrtc-img/audio.svg',
          radius: 50,
          textColor: Colors.white,
          itemFocusColor: Colors.white24,
          selectCallback: () {
            webRtcCubit.add(WebRtcSwitchAudioEvent());
          },
        ),

        LButton(
          name: '结束',
          assetImage: 'assets/webrtc-img/close.svg',
          radius: 60,
          textColor: Colors.white,
          itemBackgroundColor: Colors.red,
          itemFocusColor: Colors.redAccent,
          selectCallback: () {
            webRtcCubit.add(WebRtcCloseEvent(context));
          },
        ),

        LButton(
          name: state.isVoiceOutput ? '扬声器已开' : '扬声器已关',
          assetImage: state.isVoiceOutput ? 'assets/webrtc-img/volume.svg' : 'assets/webrtc-img/volume_close.svg',
          radius: 50,
          textColor: Colors.white,
          itemFocusColor: Colors.white24,
          selectCallback: () {
            webRtcCubit.add(WebRtcSwitchVoiceOutputEvent());
          },
        ),
      ],
    );
  }

  Widget _buildTipPane(BuildContext context, WebRtcCubit webRtcCubit) {
    var mediaList = webRtcCubit.state.mediaList.where((media)=>media.status == WebRtcUserDataStatus.connected).toList();
    var isAccept = webRtcCubit.state.isAccept;
    var message = mediaList.isEmpty ? (isAccept ? '对方邀请您语音通话': '等待对方接受连接...') : '';
    return Expanded(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [Text(message, style: const TextStyle(color: Colors.white30, fontSize: 14,
              decoration: TextDecoration.none),)],
        )
    );
  }

  Widget _buildAcceptOrRejectPane(BuildContext context, WebRtcCubit webRtcCubit) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: [
        LButton(
          name: '接受',
          assetImage: 'assets/webrtc-img/calling.svg',
          itemBackgroundColor: Colors.green,
          radius: 50,
          textColor: Colors.white,
          itemFocusColor: Colors.white24,
          selectCallback: () {
            var screenWidth = MediaQuery.of(context).size.width; // 获取屏幕宽度
            var screenHeight = MediaQuery.of(context).size.height; // 获取屏幕高度
            webRtcCubit.add(WebRtcAcceptInvitationEvent(invitationReq!, context, screenWidth, screenHeight));
          },
        ),

        LButton(
          name: '拒绝',
          assetImage: 'assets/webrtc-img/close.svg',
          itemBackgroundColor: Colors.red,
          radius: 50,
          textColor: Colors.red,
          itemFocusColor: Colors.grey,
          selectCallback: () {
            webRtcCubit.add(WebRtcRejectInvitationEvent(invitationReq!, context));
          },
        ),
      ],
    );
  }

  // 用户头像
  Widget _buildUserIcon(BuildContext context, ImUser? user) {
    if (user != null) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          UserIconView(user: user),
          const SizedBox(
            height: 10,
          ),
          Text(user.userName ?? user.userId,
            style: const TextStyle(decoration: TextDecoration.none, fontSize: 14, color: Colors.white),)
        ],
      );
    } else {
      return const Text('');
    }
  }

  Widget _buildScreenSmallView(BuildContext context, WebRtcCubit webRtcCubit, ImUser? user) {
    String timeFormat = webRtcCubit.state.timeFormat;
    if (user != null) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(timeFormat, style: const TextStyle(decoration: TextDecoration.none, fontSize: 15, color: Colors.black)),
          const SizedBox(height: 10,),
          UserIconView(user: user),
          const SizedBox(height: 5,),
          Text(user.userName ?? user.userId,
            style: const TextStyle(decoration: TextDecoration.none, fontSize: 18, color: Colors.black),)
        ],
      );
    } else {
      return const Text('');
    }
  }

  int calcMediaColumn(List<WebRtcUserData> mediaList) {
    if (mediaList.length < 4) return 2;
    if (mediaList.length < 9) return 3;
    return 3;
  }

}